package top.fyxxxx.dbdesign.servlet;

import top.fyxxxx.dbdesign.dao.DBoperate;
import top.fyxxxx.dbdesign.data.PersonalData;
import top.fyxxxx.dbdesign.util.Manager;
import top.fyxxxx.dbdesign.util.SysUtil;
import top.fyxxxx.dbdesign.util.TaskManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@WebServlet("/TaskServlet")
public class TaskServlet extends HttpServlet {
    TaskManager manager= Manager.taskManager();
    DBoperate dBoperate=DBoperate.getInstance();
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String Cid=request.getParameter("cid");
        long sid=Long.parseLong(request.getParameter("sid"));
        String sy=request.getParameter("StartTimeYear");
        String sM=request.getParameter("StartTimeMonth");
        String sd=request.getParameter("StartTimeDate");
        String sh=request.getParameter("StartTimeHour");
        String sm=request.getParameter("StartTimeMinute");
        String eh=request.getParameter("EndTimeHour");
        String em=request.getParameter("EndTimeMinute");
        if(SysUtil.hasNull(Cid,sy,sM,sm,sd,sh,eh,em)){
            ret(request,response,"0",0,sid);return;
        }
        //权限检测
        long cid=Long.parseLong(Cid);
        long uid=(Long)request.getSession().getAttribute("uid");
        PersonalData pd=dBoperate.getPersonalData(uid,cid);
        if((pd.getPower()&2)==0){
            ret(request,response,"1",cid,sid);return;
        }
        //转换时间
        SimpleDateFormat formatter=new SimpleDateFormat ("yyyy-MM-dd HH:mm");
        formatter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String st=sy+"-"+sM+"-"+sd+" ";
        String ed=st+eh+":"+em;
        st=st+sh+":"+sm;
        try {
            Date start=formatter.parse(st),end=formatter.parse(ed);
            if(start.getTime()>end.getTime()){
                ret(request,response,"2",cid,sid);return;
            }
            if(sid==0)
                manager.createTask(pd.getAccount().getUid(),start.getTime(),end.getTime(),cid);
            else manager.modifyTask(pd.getAccount().getUid(),sid,start.getTime(),end.getTime());
            ret(request,response,"3",cid,sid);
        } catch (ParseException e) {
            ret(request,response,"4",cid,sid);
        }
    }
    void ret(HttpServletRequest request, HttpServletResponse response,String res,long cid,long sid) throws IOException {
        response.sendRedirect("assignments.jsp?Message="+res+"&sid="+sid+"&cid="+cid);
    }
}
